import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:yuellyfactory/views/Controller/RuleController.dart';

import '../../components/NoScrollbarBehavior.dart';
import '../../util/BaseRequest.dart';
import '../../util/ColorUtil.dart';
import '../../util/ToastUtil.dart';
import '../../util/ViewUtil.dart';
import '../dto/PriceParm.dart';
import '../dto/PricePart.dart';
import '../dto/PriceRule.dart';

class RuleView extends StatefulWidget {

  final PricePart pricePart;
  final PriceParm priceParm;
  final RuleController controller;
  final int type;
  const RuleView(this.pricePart,this.controller,this.priceParm, {super.key, required this.type});

  @override
  State<RuleView> createState() => _RuleViewState();
}

class _RuleViewState extends State<RuleView> {


  final popoverController = ShadPopoverController();

  List<PriceRule> rules=[];
  Map idNams={};

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    widget.controller.getRules=(){
      widget.controller.settingRules!(getRule());
    };
    getAllParms();
  }
  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [

        Row(
          children: [
            ShadPopover(
              controller: popoverController,
              popover: (context) => _buildPopoverContent(),

              child: ViewUtil.textButton(
                '新增公式项',
                10,
                15,
                ViewUtil.radio(15),
                ColorUtil.colorBlue,
                ColorUtil.colorBlue,
                Colors.white,
                ViewUtil.fontSize(20),
                    () {
                  popoverController.show();
                },
              ),
            ),
            const SizedBox(width: 10,),
            ViewUtil.textButton(
              '清空公式项',
              10,
              15,
              ViewUtil.radio(15),
              ColorUtil.colorBlue,
              ColorUtil.colorBlue,
              Colors.white,
              ViewUtil.fontSize(20),
                  () {
                    rules=[];
                    setState(() {

                    });
              },
            ),
          ],
        ),

        ScrollConfiguration(
          behavior: NoScrollbarBehavior(),
          child: SingleChildScrollView(
            child:
            Padding(
              padding: const EdgeInsets.all(5.0),
              child:
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: getAllWidget(),
              )
              ,
            ),),
        )
      ],
    );
  }


  List<Widget> getAllWidget(){
    List<Widget> views=[];

    for(var i=0;i<rules.length;i++){
      PriceRule priceRule=rules[i];
      if(priceRule.handle==0){
        views.add(const SizedBox(height: 10,));
        views.add(
          KeyedSubtree(
            key: ValueKey(priceRule), // 关键：添加唯一Key
            child: inputWidget(priceRule, i),
          ),
        );
      }else{
        views.add(const SizedBox(height: 10,));
        views.add(
          KeyedSubtree(
            key: ValueKey(priceRule), // 关键：添加唯一Key
            child: selectWidget(priceRule, i),
          ),
        );
      }
    }

    return views;
  }


  Widget selectWidget(PriceRule rule,int position) {
    return Row(
      // 让Row占满父级宽度
      mainAxisSize: MainAxisSize.max,
      children: [
        // 用Expanded让输入框填充Row的可用空间
        Expanded(
          flex: 1,
          child:ShadSelectFormField<String>(

            onChanged: (value){
              debugPrint(value);
              rule.value=value!;
              widget.controller.settingRules!(getRule());
            },
            minWidth: 800,
            initialValue: rule.value,
            options: (idNams).entries
                .map((e) => ShadOption(value: e.key.toString(), child: Text(e.value.toString())))
                .toList(), // 注意添加toList()转换
            selectedOptionBuilder: (context, value) {
              if (value == null || value == 'none') {
                return const Text('请选择零件');
              }
              // 使用空值合并运算符??代替!，提供默认值
              return Text((idNams)[value]?.toString() ?? '请选择');
            },

            validator: (v) {
              if (v == null) {
                return '请选择';
              }
              return null;
            },
          ),
        ),
        Expanded(
            flex: 1,
            child: Row(
              children: [
                ShadButton.destructive(
                  child: const Text('删除'),
                  onPressed: () {
                    rules.removeAt(position);
                    setState(() {

                    });
                    widget.controller.settingRules!(getRule());
                  },
                ),
                Visibility(
                    visible: position!=0,
                    child: ShadButton(
                      child: const Text('上移'),
                      onPressed: () {
                        moveUp(position);

                      },
                    ))
                ,
                Visibility(
                    visible: position!=rules.length-1,
                    child: ShadButton(
                      child: const Text('下移'),
                      onPressed: () {
                        moveDown(position);
                      },
                    ))
                ,
              ],

            ))
      ],
    );
  }



  Widget inputWidget(PriceRule rule,int position) {
    return Row(
      // 让Row占满父级宽度
      mainAxisSize: MainAxisSize.max,
      children: [
        // 用Expanded让输入框填充Row的可用空间
        Expanded(
          flex: 1,
          child: ShadInputFormField(
            initialValue: rule.value,
            placeholder: const Text('请输入'),
            // 给输入框添加最小宽度约束（可选）
            validator: (v) {
              if (v == null || v.isEmpty) { // 注意处理null情况
                return '请输入';
              }
              return null;
            },
            onChanged: (value) {
              rule.value = value ?? ''; // 处理null情况
              widget.controller.settingRules!(getRule());
            },
          ),
        ),
        Expanded(
            flex: 1,
            child: Row(
              children: [
                ShadButton.destructive(
                  child: const Text('删除'),
                  onPressed: () {
                    rules.removeAt(position);
                    setState(() {

                    });
                    widget.controller.settingRules!(getRule());
                  },
                ),
                Visibility(
                    visible: position!=0,
                    child: ShadButton(
                      child: const Text('上移'),
                      onPressed: () {
                        moveUp(position);

                      },
                    ))
                ,
                Visibility(
                    visible: position!=rules.length-1,
                    child: ShadButton(
                      child: const Text('下移'),
                      onPressed: () {
                        moveDown(position);
                      },
                    ))
                ,
              ],

            ))
      ],
    );
  }

  // 上移操作
  void moveUp(int index) {
    if (index <= 0) return; // 已经是第一个元素，不能上移

    setState(() {
      // 交换当前元素和前一个元素的位置
      PriceRule temp = rules[index];
      rules[index] = rules[index - 1];
      rules[index - 1] = temp;
    });
    widget.controller.settingRules!(getRule());
  }

  // 下移操作
  void moveDown(int index) {
    if (index >= rules.length - 1) return; // 已经是最后一个元素，不能下移
    setState(() {
      // 交换当前元素和后一个元素的位置
      PriceRule temp = rules[index];
      rules[index] = rules[index + 1];
      rules[index + 1] = temp;
    });
    widget.controller.settingRules!(getRule());
  }


  addInput(){
    PriceRule priceRule=PriceRule();
    priceRule.handle=0;
    rules.add(priceRule);
    setState(() {

    });
    widget.controller.settingRules!(getRule());
  }
  addSelect(){
    PriceRule priceRule=PriceRule();
    priceRule.handle=1;
    rules.add(priceRule);
    setState(() {

    });
    widget.controller.settingRules!(getRule());
  }



  Widget _buildPopoverContent() {
    return SizedBox(
      width: 100,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          const Text(
            '请选择录入方式',

          ),

          const SizedBox(height: 4),
          ShadButton.outline(
            onPressed:(){
              debugPrint('录入数据');
              addInput();
              popoverController.hide();
            },
            child: const Text('录入数据'),
          ),
          const SizedBox(height: 4),
          ShadButton.outline(
            onPressed:(){
              debugPrint('选择参数');
              addSelect();
              popoverController.hide();
            },
            child: const Text('选择参数'),
          )

        ],
      ),
    );
  }


  void getAllParms(){
    var parm={
      "id":widget.pricePart.id,
    };
    var url='price/getallparam';
    if(widget.type==1){
      url='price/getallmaterialparam';
    }
    BaseRequest.postHttp(url,parameters: parm, canTip: true, context: context, onSuccess: (data){
      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        dynamic datas=data["data"];
        List allParms=[];
        for(var i=0;i<datas.length;i++){
          var item=datas[i];
          var part=PriceParm.fromJson(item);


          if(part.id!=widget.priceParm.id){
            idNams[part.id]=part.name;
            allParms.add(part);
          }

        }

      }
      initDatas();

    }, onError: (error){


    });
  }

   getRule(){
    bool result=true;
    List datas=[];
    for(PriceRule parm in rules){
      if(parm.value.isEmpty){
        result=false;
        break;
      }
      if(parm.handle==1){
        parm.name=idNams[parm.value]??"";
      }
      datas.add(parm.toJson());
    }
    if(!result){
      return [];

    }
    return datas;

  }
  void initDatas(){
    if(widget.priceParm.rule.isNotEmpty){
      List<dynamic> list = json.decode(widget.priceParm.rule);
      List<PriceRule> ruleList=[];
      for(var item in list){
        PriceRule rule=PriceRule.fromJson(item);
        ruleList.add(rule);
      }
      rules=ruleList;
      setState(() {

      });
      widget.controller.settingRules!(getRule());
    }
  }
}
